﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FromProject
{
    public partial class Form1 : Form
    {
        //启动路径
        private string path = "";
        //日志内容
        private string content = "";
        //启动程序
        private Process myNewProcess = new Process();
        //是否开始
        private bool IsOK = false;
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //查找MessageBox的弹出窗口,注意对应标题
            IntPtr ptr = FindWindow(null, txttc.Text);
            if (ptr != IntPtr.Zero)
            {
                try
                {
                    if (!string.IsNullOrWhiteSpace(txtjc.Text))
                    {
                        Process[] ps = Process.GetProcessesByName(txtjc.Text);
                        path = ps[0].MainModule.FileName;
                        if (ps.Count() > 0)
                        {
                            for (int i = 0; i < ps.Count(); i++)
                            {
                                ps[i].Kill();
                                content = "时间:" + DateTime.Now.ToString() + ",   关闭进程:" + ps[i].ProcessName + "";
                                WriteLog(content);
                            }
                        }
                        //要启动的应用程序
                        myNewProcess.StartInfo.FileName = path;
                        myNewProcess.StartInfo.UseShellExecute = false;
                        // 设置要启动的进程的初始目录
                        myNewProcess.StartInfo.WorkingDirectory = Application.ExecutablePath;
                        //启动程序
                        myNewProcess.Start();
                    }
                    else
                    {
                        GetWindowThreadProcessId(ptr, out int pid);
                        Process[] ps = Process.GetProcesses();
                        if (ps.Length > 0)
                        {
                            foreach (var item in ps)
                            {
                                if (item.Id == pid)
                                {
                                    //获取启动路径
                                    path = item.MainModule.FileName;
                                    //关闭该程序所有进程
                                    Process[] processes = Process.GetProcessesByName(item.ProcessName);
                                    if (processes.Count() > 0)
                                    {
                                        for (int i = 0; i < processes.Count(); i++)
                                        {
                                            processes[i].Kill();
                                            content = "时间:" + DateTime.Now.ToString() + ",   关闭进程:" + processes[i].ProcessName + "";
                                            WriteLog(content);
                                        }
                                    }
                                    //要启动的应用程序
                                    myNewProcess.StartInfo.FileName = path;
                                    myNewProcess.StartInfo.UseShellExecute = false;
                                    // 设置要启动的进程的初始目录
                                    myNewProcess.StartInfo.WorkingDirectory = Application.ExecutablePath;
                                    //启动程序
                                    myNewProcess.Start();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteLog(ex.Message);
                    throw;
                }
            }

        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            // 判断只有最小化时，隐藏窗体
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // 正常显示窗体
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        public static void WriteLog(string content)
        {
            //获取基目录
            string path = AppDomain.CurrentDomain.BaseDirectory + "log.txt";
            if (!File.Exists(path))
            {
                //如果不存在创建文件
                FileStream stream = File.Create(path);
                stream.Close();
                stream.Dispose();
            }
            using (StreamWriter writer = new StreamWriter(path, true))
            {
                writer.WriteLine(content);
            }
        }

        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        /// <summary>
        /// 根据句柄获得进程id值
        /// </summary>
        /// <param name="handle">句柄</param>
        /// <param name="pid"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        private static extern int GetWindowThreadProcessId(IntPtr handle, out int pid);

        private void btn1_Click(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(txttc.Text))
                {
                    //开始任务
                    if (!IsOK)
                    {
                        btn1.Text = "停止";
                        IsOK = true;
                        if (!string.IsNullOrWhiteSpace(txttime.Text))
                        {
                            timer1.Interval = int.TryParse(txttime.Text, out int time) ? time * 1000 : 5000;
                        }
                        timer1.Enabled = true;
                        timer1.Start();
                    }
                    else if (IsOK)
                    {
                        btn1.Text = "开始";
                        IsOK = false;
                        timer1.Enabled = false;
                        timer1.Stop();
                    }
                }
                else
                {
                    MessageBox.Show("必填项不能为空");
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message);
                throw;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            btn1.Text = "开始";
            timer1.Interval = 5000;
            timer1.Enabled = false;
            timer1.Stop();
        }
    }
}
